package com.komon.object.request;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.Map;

import com.komon.annotation.State;

@State //socketInputStream
public class SimpleHttpRequest {
	private final RequestLine requestLine;
	private final Map<String,String> headers;
	private final InputStream socketInputStream;
	
	public SimpleHttpRequest(RequestLine requestLine, Map<String, String> headers,
			 InputStream socketInputStream) throws UnsupportedEncodingException {
		this.requestLine = requestLine;
		this.headers = headers;
		this.socketInputStream = socketInputStream;
		/*
		String contentType = this.getHeader("Content-Type");
		MediaType mediaType = new MediaType(contentType);
		
		String charSet = null;
		//see rfc 2616 3.7.1 
		if ("Text".equalsIgnoreCase(mediaType.getType())) {
			charSet = mediaType.getAttributeValue("charSet");
			if (CommonUtils.isEmptyString(charSet)) {
				charSet = Configuration.DEFAULT_REQ_BODY_ENCODING;
			}
			this.bodyReader = new BufferedReader(new InputStreamReader(inputStream, charSet));
		} else {
			//TODO empty bodyReader
			this.bodyReader = null;
		}*/
	}
	
	/**
	 * @return the requestLine
	 */
	public RequestLine getRequestLine() {
		return requestLine;
	}

	public Map<String, String> getHeaders() {
		return Collections.unmodifiableMap(headers);
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		sb.append(requestLine).append("\n");
		
		for (Map.Entry<String, String> entry : headers.entrySet()) {
			sb.append(entry.getKey()).append(":").append(entry.getValue()).append("\n");
		}
		return sb.toString();
		
	}
	
	public String getHeader(String name) {
		String headerValue = null;
		//case insensitive
		for (Map.Entry<String, String> entry : headers.entrySet()) {
			if (entry.getKey().equalsIgnoreCase(name)) {
				headerValue =  entry.getValue();
				break;
			}
		}
		//return the first one
		if (headerValue != null && headerValue.contains(",")) {
			return headerValue.substring(0,headerValue.indexOf(','));
		}
		return headerValue;
	}
	/**
	 * @return the socketInputStream
	 */
	public InputStream getSocketInputStream() {
		return socketInputStream;
	}
}
